#include "../lib/coresplitter.hpp"
#include "../lib/coreutil.hpp"
using namespace pland;

Splitter_Copy::Splitter_Copy()
{
    running_ = false;
}

void Splitter_Copy::loadQueues(SharedDQueue front, std::vector<SharedDQueue> back)
{
    boost::unique_lock< boost::shared_mutex > lock(mutex_);
    front_ = front;
    back_ = back;
}

bool Splitter_Copy::start()
{
    boost::unique_lock< boost::shared_mutex > lock(mutex_);
    if(running_ == true)
    {
        return false;
    }
    thread_ = boost::thread(&Splitter_Copy::start_, this);
    return running_;
}

bool Splitter_Copy::stop()
{
    boost::unique_lock< boost::shared_mutex > lock(mutex_);
    if(running_ == false)
    {
        return false;
    }
    thread_.interrupt();
    thread_.join();
    running_ = false;
    return running_;
}

void Splitter_Copy::start_()
{
    try
    {
        running_= true;
        utill_log(std::string(__FILE__) + " Started spliter thread");
        while(1)
        {
            SharedData next = front_->pop();
            for(uint i = 0; i< back_.size(); i++)
            {
                SharedData copy(new Data(*next));
                back_.at(i)->push(copy);
            }
        }
    }
    catch(boost::thread_interrupted e)
    {
        utill_log(std::string(__FILE__) + " Stopped spliter thread");
        running_ = false;
        return;
    }
}


///////////////////////////////////////////////Balancer

Splitter_Balancer::Splitter_Balancer()
{
    running_ = false;
}

void Splitter_Balancer::loadQueues(SharedDQueue front, std::vector<SharedDQueue> back)
{
    front_ = front;
    back_ = back;
    turn = 0;
}

bool Splitter_Balancer::start()
{
    boost::unique_lock< boost::shared_mutex > lock(mutex_);
    if(running_ == true)
    {
        return false;
    }
    running_ = true;
    thread_ = boost::thread(&Splitter_Balancer::start_, this);
    return running_;
}

bool Splitter_Balancer::stop()
{
    boost::unique_lock< boost::shared_mutex > lock(mutex_);
    if(running_ == false)
    {
        return false;
    }
    thread_.interrupt();
    thread_.join();
    running_ = false;
    return running_;
}

void Splitter_Balancer::start_()
{
    try
    {
        running_= true;
        utill_log(std::string(__FILE__) + " Started spliter thread");
        while(1)
        {
            SharedData next = front_->pop();
            for(uint i = 0; i< back_.size(); i++)
            {
                SharedData next = front_->pop();
                if(turn == back_.size())
                    turn = 0;
                SharedData copy(new Data(*next));
                back_.at(turn)->push(copy);
                turn++;
            }
        }
    }
    catch(boost::thread_interrupted e)
    {
        utill_log(std::string(__FILE__) + " Stopped spliter thread");
        turn = 0;
        running_ = false;
        return;
    }
}
